package com.hewep.view;

import java.io.IOException;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class ModalDialog extends AnchorPane{
	public enum Type { ALERT, ERROR, INFO, CONFIRM };
	private boolean reValue;
	private Stage stage;
	
	private Label infoLbl;
	private HBox btnCtrl;
	
	public ModalDialog(Type t, String info){
		stage = new Stage(StageStyle.UTILITY);
		stage.initModality(Modality.APPLICATION_MODAL);
		stage.setMaxWidth(Screen.getPrimary().getVisualBounds().getWidth() / 2);
		
		FXMLLoader fxml = new FXMLLoader(getClass().getResource("res/dialog.fxml"));
		fxml.setController(this);
		try {
			Parent parent = fxml.load();
			this.getChildren().add((Node)parent);
			
			infoLbl = (Label)parent.lookup("#info");
			infoLbl.setText(info);
			btnCtrl = (HBox) parent.lookup("#btn-ctrl");
			
			this.initDialog(t);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void initDialog(Type t){
		Button close = new Button("关 闭");
    	close.setId("close");
    	close.getStyleClass().addAll("btn-mini","btn-alert");
    	close.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent arg0) {
				// TODO Auto-generated method stub
				reValue = false;
				stage.close();
			}
		});
		
		Region spacer = new Region();
		HBox.setHgrow(spacer, Priority.ALWAYS);
		switch (t) {
        case ALERT:
        	btnCtrl.getChildren().addAll(spacer, close);
            break;
        case ERROR:
            break;
        case INFO:
            break;
        case CONFIRM:
        	Button ok = new Button("确 定");
    		ok.setId("ok");
    		ok.getStyleClass().addAll("btn-mini","btn-success");
    		ok.setOnAction(new EventHandler<ActionEvent>() {
    			
    			@Override
    			public void handle(ActionEvent arg0) {
    				// TODO Auto-generated method stub
    				
    				reValue = true;
    				stage.close();
    			}
    		});
        	btnCtrl.getChildren().addAll(ok, spacer, close);
        	
            break;
        default:
            break;
		}
	}
	
	public boolean show(){
		this.stage.setScene(new Scene(this));
		this.stage.showAndWait();
		return reValue;
	}
}
